Imports System.Xml
Imports System.net

Public Class CPCInterface

	Protected m_url As String = ""
	Protected m_msg As String = ""
	Protected m_reply As String = ""
	Protected m_sesscookie As String = ""

	Public Property URL() As String
		Get
			Return m_url
		End Get
		Set(ByVal Value As String)
			m_url = Value
		End Set
	End Property

	Public Property Message() As String
		Get
			Return m_msg
		End Get
		Set(ByVal Value As String)
			m_msg = Value
		End Set
	End Property

	Public ReadOnly Property ReplyMsg() As String
		Get
			Return m_reply
		End Get
	End Property

	Public ReadOnly Property ReplyXml() As XmlDocument
		Get
			Dim sxml As XmlDocument = New XmlDocument
			sxml.LoadXml(m_reply)

			Return sxml
		End Get
	End Property

	Public Sub New()
		m_url = Globals.APIUrl

	End Sub

	Public Sub Reset()
		m_msg = ""
		m_reply = ""
	End Sub

	Public Function SendMessage() As Boolean
		Dim sxml As XmlDocument = New XmlDocument
		sxml.LoadXml(m_msg)

		m_reply = SubmitDoc(sxml)

        If m_reply = "" Then
            m_reply = SubmitDoc(sxml)

            If m_reply = "" Then
                Return False
            End If
        End If
        '		m_reply = sxml.OuterXml
        Return True

	End Function

	Private Function SubmitDoc(ByVal xDoc As XmlDocument) As String

		Try

			Dim bdata As Byte() = System.Text.Encoding.UTF8.GetBytes(xDoc.OuterXml)

			Dim wc As WebClient = Globals.WebClient
			Dim bresp As Byte()

			wc.Headers.Add("Content-Type", "text/xml")
			If m_sesscookie <> "" Then
				wc.Headers.Add("Cookie", m_sesscookie)
			End If
			bresp = wc.UploadData(URL, bdata)

			Dim resp As String = System.Text.Encoding.UTF8.GetString(bresp)

			If Not wc.ResponseHeaders("Set-Cookie") Is Nothing Then
				m_sesscookie = wc.ResponseHeaders("Set-Cookie")
			End If
			'			Dim xresp As XmlDocument = New XmlDocument
			'			xresp.LoadXml(resp)

            wc.Dispose()
            wc = Nothing
			Return resp
        Catch ex As Exception
            Log.LogData(ex.Message)
            Globals.WebClient = Nothing
            Return ""

        End Try

	End Function

End Class
